package com.douqu.game.core.entity.db;

import com.bean.core.buffer.ByteBuffer;
import com.douqu.game.core.entity.Player;
import com.douqu.game.core.entity.ext.BagInfo;
import com.douqu.game.core.entity.ext.data.BaseData;
import com.douqu.game.core.entity.ext.data.timeLimit.TimePropDB;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author wangzhenfei
 *         2018-04-18 11:33
 *         时效性道具
 */
public class TimePropData extends BaseData{
    /**玩家所有时效性道具map*/
    private Map<String,TimePropDB> timePropMap;

    /**玩家所有时效性道具list */
    private List<TimePropDB> timePropList;

    protected Player player;

    private BagInfo bagInfo;

    public TimePropData(Player player, BagInfo bagInfo){
        this.player = player;
        this.bagInfo = bagInfo;
        timePropMap = new ConcurrentHashMap<>();
        timePropList = new CopyOnWriteArrayList<>();
    }


    @Override
    public void init() {

    }

    @Override
    public void checkInit() {

    }

    @Override
    public void reset() {
        for(TimePropDB timeDB : timePropList){
            if(timeDB.isCanDelete()){
                removeTimeProp(timeDB.uniqueId);
            }
        }
    }

    @Override
    public void checkReset() {
       reset();
    }

    @Override
    public void writeTo(ByteBuffer buffer) {
        buffer.writeShort(timePropList.size());
        for(TimePropDB db : timePropList){
            db.writeTo(buffer);
        }
        buffer.writeBoolean(false);
    }

    @Override
    public void loadFrom(ByteBuffer buffer) {
        int size = buffer.readShort();
        TimePropDB db = null;
        for(int i = 0; i < size; i++){
            db = new TimePropDB();
            db.loadFrom(buffer);
            addTimeProp(db);
        }
        buffer.readBoolean();
    }

    /**
     * 获取时效性道具
     * @param uniqueId
     */
    public TimePropDB getTimeProp(String uniqueId){
        return timePropMap.get(uniqueId);
    }


    /**
     * 增加道具
     * @param db
     */
    public void addTimeProp(TimePropDB db){
        if(db == null || !db.isTimeIn()){
            return;
        }
        timePropMap.put(db.uniqueId, db);
        timePropList.add(db);

    }


    /**
     * 删除道具
     * @param uniqueId
     */
    public void removeTimeProp(String uniqueId){
        TimePropDB timeDB = timePropMap.get(uniqueId);
        if(timeDB != null){
            timePropMap.remove(timeDB.uniqueId);
            timePropList.remove(timeDB);
        }
    }

    public List<TimePropDB> getTimePropList() {
        return timePropList;
    }
}
